/*
 * DataRegServlet.java
 *
 * Created on 4 Ноябрь 2006 г., 16:07
 */

package authregistration;

import javax.sql.*;
import java.sql.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import crypto.GetPassword;
import crypto.UserPasswordCheck;

import javax.annotation.Resource;
import javax.transaction.*;
import javax.ejb.EJB;
import helpfunctons.entity.*;
import helpfunctons.entity.beans.*;

public class DataRegServlet extends HttpServlet {
    private static final String CONTENT_TYPE =
            "text/html; charset=windows-1251";
    //Initialize global variables
   
    //Init EJBs
    /**
     * EJB stub for Entity gameusers
     */
    @EJB
    private GameusersFacadeLocal gamef;
    /**
     * EJB stub for Entity Players
     */
    @EJB
    private PlayersFacadeLocal playf;
    /**
     * User Resource Transaction
     */
    @Resource
    private UserTransaction utx;
    
    //init Entity
    /**
     * Gameuser class
     */
    private Gameusers user;
    private Players player;
    //init vars
    String username = null;
    String firstname = null;
    String lastname = null;
    String email = null;
    String password = null;
    String cpassword = null;
    String hash = null;
    String ipadress = null;
    PrintWriter out=null;
    
    
    //Process the HTTP Get request
    /**
     *
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        
        Context env = null;
        Connection conn = null;
        DataSource pool = null;
        ServletContext context = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
        

            out = response.getWriter();
            utx.begin();
                //context = getServletContext();
                //Class.forName(com.mysql.jdbc.Driver.class.getName());
                //env = (Context)new InitialContext().lookup("java:comp/env");
                //pool = (DataSource) env.lookup("jdbc/user");
                //conn = pool.getConnection();
                //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?user=root&password=tolstyak");
            
            username = request.getParameter("username");
            firstname = request.getParameter("firstname");
            lastname = request.getParameter("lastname");
            email = request.getParameter("email");
            password = request.getParameter("password");
            cpassword = request.getParameter("cpassword");
            ipadress = request.getLocalAddr();
            this.dataWrite();
            
            CookieReadWriter cookie = new CookieReadWriter();
            cookie.putLoginCookie(response,username,email,"1");
            cookie.putNameCookie(response,username);
            
            this.playerEJBCreate();
            playf.edit(player);
            gamef.edit(user);
            gamef.update();
            utx.commit();
            out.close();
        } catch (NotSupportedException ex) {
            ex.printStackTrace();
        } catch (SystemException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }
    
    void playerEJBCreate(){
        player = new Players(username);
        player.setUser(this.user);
        player.setMoneybank(100);
        user.setPlayer(this.player);
    }            
    
    @Deprecated    
    boolean playerCreate(Connection conn,Statement stmt,ResultSet rs,ServletContext context) {
        try {
            String insertstr = "INSERT INTO players VALUES('"+0+"','"+username
                    +"','"+100+"','"+null+"','"+
                    0+"','"+0+"','"+0+"','"+0+"');";
            stmt = conn.createStatement();
            return stmt.execute(insertstr);
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }
    
    void dataWrite(){
        Gameusers user = new Gameusers(username);
        user.setEmail(this.email);
        user.setFirstname(this.firstname);
        user.setId(gamef.getID());
        user.setIp(this.ipadress);
        user.setLastname(this.lastname);
        user.setPassword(crypto.UserPasswordCheck.putIntoDateBase(username, password));
        user.setRegdate(new java.sql.Date(System.currentTimeMillis()));

    }
    
    @Deprecated 
    boolean dataWrite(Connection conn,Statement stmt,ResultSet rs,ServletContext context) {
        try {
            java.sql.Date nowdate = new java.sql.Date(System.currentTimeMillis());
            //Check password==cpassword
            //we do it in js
            //Generated Password for a User
            hash = crypto.UserPasswordCheck.putIntoDateBase(username, password);
            //Create Connection
            stmt = conn.createStatement();
            String insertstr = "INSERT INTO gameusers VALUES('"+0+"','" + username +
                    "','" + hash + "','"
                    + firstname + "','" + lastname + "','" + email +
                    "','"+nowdate+"','"+ipadress+"');";
            return stmt.execute(insertstr);
        } catch (SQLException ex) {
            out.println("<h2>"+ex.getMessage()+"</h2>");
            return false;
        }
    }
    
    //Process the HTTP Post request
    /**
     *
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }
    
    //Clean up resources
    /**
     * Free EntityManager
     */
    public void destroy() {
    }
}
